import { login, logout, getInfo, appIndexConfigGet } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.png'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      userInfo: {},
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: [],
      appInfo: {}
    }),
    actions: {
      // 登录
      login (userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const code = userInfo.code
        const uuid = userInfo.uuid
        return new Promise((resolve, reject) => {
          login(username, password, code, uuid).then(res => {
            setToken(res.data)
            this.token = res.data
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo () {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res.data
            const avatar = (user.pic == "" || user.pic == null) ? defAva : user.pic;

            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.userInfo = user
            this.id = user.id
            this.name = user.nickname
            this.avatar = avatar
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      getBaseAppInfo () {
        return appIndexConfigGet().then(res => {
          this.appInfo = res.data
        })
      },
      // 退出系统
      logOut () {
        return new Promise((resolve, reject) => {
          this.token = ''
          this.roles = []
          this.permissions = []
          this.userInfo = {}
          this.id = ''
          this.name = ''
          this.avatar = ''
          removeToken()
          resolve()
          // logout(this.token).then(() => {
          //   this.token = ''
          //   this.roles = []
          //   this.permissions = []
          //   removeToken()
          //   resolve()
          // }).catch(error => {
          //   reject(error)
          // })
        })
      }
    }
  }
)

export default useUserStore
